/*
*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*  WSO2 Inc. licenses this file to you under the Apache License,
*  Version 2.0 (the "License"); you may not use this file except
*  in compliance with the License.
*  You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.bpel.b4p.axis2.receiver;

import org.apache.axis2.receivers.AbstractInMessageReceiver;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.AxisFault;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPHeaderBlock;
import org.wso2.carbon.bpel.b4p.extension.B4PExtensionOperation;
import org.wso2.carbon.bpel.b4p.extension.B4PMessage;
import org.wso2.carbon.bpel.b4p.utils.SOAPHelper;
import org.wso2.carbon.bpel.b4p.utils.Constants;

import javax.xml.namespace.QName;
import java.util.concurrent.CountDownLatch;
import java.util.Iterator;

public class HumanMessageReceiver extends AbstractInMessageReceiver {
    private static Log log = LogFactory.getLog(HumanMessageReceiver.class);

    private SOAPHelper soapHelper;

    protected void invokeBusinessLogic(MessageContext messageContext) throws AxisFault {
        if (log.isDebugEnabled()) {
            log.debug("HT Response Received: " + messageContext.getEnvelope());
        }
        String taskID = getTaskID(messageContext.getEnvelope());
        if (taskID == null) {
            log.warn("TaskID not available. Ignored!");
            return;
        }
        CountDownLatch cdl = B4PExtensionOperation.countDownLatches.remove(taskID);
        if (cdl == null) {
            log.warn("Invalid SOAP message. Ignored!");
            return;
        }

        B4PMessage response = new B4PMessage();
        soapHelper.parseSoapResponse(response, messageContext.getEnvelope(), null);
        B4PExtensionOperation.outPutVarElementMap.put(taskID, response.getMessage());
        if (log.isDebugEnabled()) {
            log.debug(taskID + ": latch countdown");
        }
        cdl.countDown();
    }

    private String getTaskID(SOAPEnvelope envelope) {
        /*
        * <soapenv:Header>
        * <axis2ns1:feedback xmlns:axis2ns1="http://wso2.org/humantask/feedback" 
        * soapenv:actor="http://schemas.xmlsoap.org/soap/envelope/actor/feedback" axis2ns1:taskid="500" />
        * </soapenv:Header>
        * */
        String taskID = null;
        Iterator hbIterator = envelope.getHeader().examineHeaderBlocks(Constants.FEEDBACK_HEADER_ROLE_URI);
        while (hbIterator.hasNext()) {
            SOAPHeaderBlock soapHeaderBlock = (SOAPHeaderBlock)hbIterator.next();
            if (soapHeaderBlock.getLocalName().equals(Constants.FEEDBACK_HEADER_LOCALNAME)) {
                taskID = soapHeaderBlock.getAttributeValue(new QName(Constants.FEEDBACK_ATTRIBUTE_NAMESPACE,
                        Constants.FEEDBACK_ATTRIBUTE_NAME));
                break;
            }
        }
        
        log.info(taskID + " :TaskID: " + taskID);
        return taskID;
    }

    public void setSoapHelper(SOAPHelper soapHelper) {
        this.soapHelper = soapHelper;
    }
}
